import Footer from '@/components/Footer';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, Col, message, Row } from 'antd';
import Settings from '../../../config/defaultSettings';
import React, { useState } from 'react';
import BannerImage from '@/pages/Login/Banner';
import LoginBg from '@/pages/Login/LoginBg';
import styles from './style.less';
import { login } from '@/services/system/user';
import { FormattedMessage, useIntl } from '@@/plugin-locale/localeExports';

import { useModel, Helmet, history } from '@umijs/max';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { flushSync } from 'react-dom';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({ code: 0 });
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log(userInfo);
    if (userInfo) {
      flushSync(() => {
        setInitialState({
          ...initialState,
          currentUser: userInfo,
        });
      });
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      const { code, msg, data } = await login({ ...values });
      if (code === 0) {
        localStorage.setItem('ACCESS_TOKEN', JSON.stringify(data));
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        history.push(urlParams.get('redirect') || '/');
        message.success(defaultLoginSuccessMessage);
        return;
      }
      setUserLoginState({ code, msg });
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    }
  };
  const { code, msg } = userLoginState;

  return (
    <div className={styles.container}>
      <LoginBg />
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>

      <Row justify={'center'} align={'middle'} className={styles.login}>
        <Col className={styles.loginLeft}>
          {' '}
          <BannerImage />
        </Col>
        <Col className={styles.loginRight}>
          <LoginForm
            logo={<img alt="logo" src="/logo_color.svg" />}
            title={intl.formatMessage({ id: 'layout.title' })}
            subTitle={intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
            initialValues={{
              autoLogin: true,
            }}
            actions={[]}
            onFinish={async (values) => {
              await handleSubmit(values);
            }}
          >
            {code !== 0 && (
              <LoginMessage
                content={
                  msg ||
                  intl.formatMessage({
                    id: 'pages.login.accountLogin.errorMessage',
                    defaultMessage: '账户或密码错误',
                  })
                }
              />
            )}
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '请输入用户名',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
          </LoginForm>
        </Col>
      </Row>
      <Footer />
    </div>
  );
};

export default Login;
